package cli;

import java.awt.Color;
import java.awt.Point;
import java.util.ArrayList;

import base.Engine;
import base.Piece;
import base.Set;
import base.State;
import base.VirtualBoard;

public class BoardWidget {
	private ArrayList<String> board = new ArrayList<String>();
	private StringBuilder stringBuilder;
	private VirtualBoard virtualBoard;
	private Set set;
	private Engine engine;
	
	public BoardWidget(Engine engine) {
		this.setEngine(engine);
		this.virtualBoard = this.getEngine().getVirtualBoard();
	}
	
	public void refreshBoard() {
		this.board.clear();
		
		for (int y = 0; y < this.virtualBoard.getSize().height; y++) {
			StringBuilder row = new StringBuilder();
			
			for (int x = 0; x < this.virtualBoard.getSize().width; x++) {
				Point location = new Point(x, y);
				String label;
				
				if (!this.virtualBoard.isEmpty(location)) {
					Piece piece = this.virtualBoard.getPiece(location);
					State state = this.virtualBoard.getCurrentState(piece);
					
					label = this.getRepresentation(state.getUpgrade());
					
					if (this.virtualBoard.getCurrentState(piece).getOwner().getColor().equals(Color.BLACK)) {
						label = label.toUpperCase();
					}
					else {
						label = label.toLowerCase();
					}
				}
				else {
					label = "*";
				}
				
				row.append(label);
			}
			
			this.board.add(row.toString());
		}
		
		this.stringBuilder = new StringBuilder();
		
		for (String row : this.board) {
			this.stringBuilder.append(row);
			this.stringBuilder.append(CLI.NEWLINE);
		}
		
		this.stringBuilder.trimToSize();
	}

	private String getRepresentation(Piece piece) {
		return this.getSet().getRepresentationByPiece(piece.getRepresentation());
	}

	public void setEngine(Engine engine) {
		this.engine = engine;
	}

	public Engine getEngine() {
		return engine;
	}

	public void setBoard(ArrayList<String> board) {
		this.board = board;
	}

	public ArrayList<String> getBoard() {
		return board;
	}

	public void setSet(Set set) {
		this.set = set;
		this.refreshBoard();
	}

	public Set getSet() {
		return set;
	}
	
	@Override
	public String toString() {
		return this.stringBuilder.toString();
	}
}
